package com.fashion.server.controller;

import com.alibaba.fastjson.TypeReference;
import com.fashion.server.common.BaseController;
import com.fashion.server.common.IConstants;
import com.fashion.server.domain.model.WebUserModel;
import com.fashion.server.domain.request.HttpDataParam;
import com.fashion.server.domain.response.ResponseData;
import com.fashion.server.service.WebUserService;
import com.fashion.server.utils.JsonUtil;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SMTPAppender;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 主播controller类
 * Created by zhuqi on 2016/9/6.
 */
@Controller
@RequestMapping("webUserCtrl")
public class WebUserController extends BaseController {

    @Resource
    private WebUserService webUserService;
    private static final Logger logger = Logger.getLogger(WebUserController.class);


    @Override
    protected void initBaseFields() {
        BASE_FIELDS.put("id","webUser.id");
        BASE_FIELDS.put("userId","webUser.user_id");
        BASE_FIELDS.put("nickName","webUser.nick_name");
        BASE_FIELDS.put("account","webUser.account");
        BASE_FIELDS.put("passwords","webUser.passwords");
        BASE_FIELDS.put("state","webUser.state");
        BASE_FIELDS.put("superiorState","webUser.superior_state");
        BASE_FIELDS.put("contractState","webUser.contract_state");
        BASE_FIELDS.put("superiorContractState","webUser.superior_contract_state");
        BASE_FIELDS.put("mobile","webUser.mobile");
        BASE_FIELDS.put("openidWx","webUser.openid_wx");
        BASE_FIELDS.put("openidWb","webUser.openid_wb");
        BASE_FIELDS.put("openidQq","webUser.openid_qq");
        BASE_FIELDS.put("createTime","webUser.create_time");
        BASE_FIELDS.put("modifyTime","webUser.modify_time");
        BASE_FIELDS.put("headImg","webUser.head_img");
        BASE_FIELDS.put("userType","webUser.user_type");
        BASE_FIELDS.put("sex","webUser.sex");
        BASE_FIELDS.put("birthday","webUser.birthday");
        BASE_FIELDS.put("qq","webUser.qq");
        BASE_FIELDS.put("address","webUser.address");
        BASE_FIELDS.put("description","webUser.description");
        BASE_FIELDS.put("personSign","webUser.person_sign");
        BASE_FIELDS.put("star","webUser.star");
        BASE_FIELDS.put("feeling","webUser.feeling");
        BASE_FIELDS.put("job","webUser.job");
        BASE_FIELDS.put("province","webUser.province");
        BASE_FIELDS.put("city","webUser.city");
        BASE_FIELDS.put("age","webUser.age");
        BASE_FIELDS.put("authId","webUser.auth_id");
        BASE_FIELDS.put("payCount","webUser.pay_count");
        BASE_FIELDS.put("hefanTotal","webUser.hefan_total");
        BASE_FIELDS.put("backGround","webUser.back_ground");
        BASE_FIELDS.put("balance","webUser.balance");
        BASE_FIELDS.put("exp","webUser.exp");
        BASE_FIELDS.put("userLevel","webUser.user_level");
        BASE_FIELDS.put("imToken","webUser.im_token");
        BASE_FIELDS.put("identity_status","webUser.identity_status");
        BASE_FIELDS.put("toClubStatus","webUser.to_club_status");
        BASE_FIELDS.put("chatRoomId","webUser.chat_room_id");
        BASE_FIELDS.put("token","webUser.token");
        BASE_FIELDS.put("gpsLocation","webUser.gps_location");
        BASE_FIELDS.put("createFromSrc","webUser.create_from_src");
        BASE_FIELDS.put("isDel","webUser.is_del");
        BASE_FIELDS.put("extraFans","webUser.extra_fans");
        BASE_FIELDS.put("bakMobile","webUser.bak_mobile");
        BASE_FIELDS.put("authInfo","webUser.auth_info");
        BASE_FIELDS.put("freezeDays","webUser.freeze_days");
        BASE_FIELDS.put("sourceUserId","webUser.source_user_id");

        //真实粉丝数
        BASE_FIELDS.put("fans_Count","(SELECT COUNT(*) FROM fans_relation f WHERE f.main_user_id = webUser.user_id) as fans_Count");
        //关注我-人数量
        BASE_FIELDS.put("watch_Count","(SELECT COUNT(*) FROM watch_relation w WHERE w.main_user_id = webUser.user_id) as watch_Count");
        //处罚数
        BASE_FIELDS.put("punish_Count","(SELECT COUNT(*) FROM punish_detail p WHERE p.user_id = webUser.user_id and p.cancel_flag=0) as punish_Count");
        //盒饭数(本月有效真实盒饭数)
        BASE_FIELDS.put("hefan_Count","(SELECT COUNT(*) FROM punish_detail h WHERE h.user_id = webUser.user_id and h.cancel_flag=0) as hefan_Count");
        //普通用户关注数
        BASE_FIELDS.put("attention_Count","(SELECT COUNT(*) FROM fans_relation f WHERE webUser.user_id=f.user_id) as attention_Count");
        
        BASE_FIELDS.put("identity.id","identity.id as identityId");
        BASE_FIELDS.put("identity.userId","identity.user_id");
        BASE_FIELDS.put("identity.realName","identity.real_name");
        BASE_FIELDS.put("identity.personId","identity.person_id");
        BASE_FIELDS.put("identity.history","identity.history");
        BASE_FIELDS.put("identity.infoFile","identity.info_file");
        BASE_FIELDS.put("identity.platForm","identity.plat_form");
        BASE_FIELDS.put("identity.liveId","identity.live_id");
        BASE_FIELDS.put("identity.bankId","identity.bank_id");
        BASE_FIELDS.put("identity.personImg","identity.person_img");
        BASE_FIELDS.put("identity.personImgByHand","identity.person_img_byHand");
        BASE_FIELDS.put("identity.personImgHeads","identity.person_img_heads");
        BASE_FIELDS.put("identity.personImgTails","identity.person_img_tails");
        BASE_FIELDS.put("identity.signStartTime","identity.sign_start_time");
        BASE_FIELDS.put("identity.signEndTime","identity.sign_end_time");
        BASE_FIELDS.put("identity.bank","identity.bank");
        BASE_FIELDS.put("identity.bankName","identity.bank_name");
        BASE_FIELDS.put("identity.levelId","identity.level_id");
        BASE_FIELDS.put("identity.ruleDay","identity.rule_day");
        BASE_FIELDS.put("identity.ruleTime","identity.rule_time");
        BASE_FIELDS.put("identity.validTime","identity.valid_time");
        BASE_FIELDS.put("identity.groupId","identity.group_id");
        BASE_FIELDS.put("identity.basicSalary","identity.basic_salary");
        BASE_FIELDS.put("identity.platformIntoRatio","identity.platform_into_ratio");
        BASE_FIELDS.put("identity.groupIntoRatio","identity.group_into_ratio");
        BASE_FIELDS.put("identity.personalIntoRatio","identity.personal_into_ratio");
        BASE_FIELDS.put("identity.status","identity.status");
        BASE_FIELDS.put("identity.pid","identity.pid");
        BASE_FIELDS.put("identity.bgimg","identity.bgimg");
        BASE_FIELDS.put("identity.profiles","identity.profiles");
        BASE_FIELDS.put("identity.relationIds","identity.relation_ids");
        BASE_FIELDS.put("identity.operationId","identity.operation_id");
        BASE_FIELDS.put("identity.firstShow","identity.first_show");
        BASE_FIELDS.put("identity.contactPhone","identity.contact_phone");
        BASE_FIELDS.put("identity.applyTime","identity.apply_time");
        BASE_FIELDS.put("identity.superiorInto","identity.superior_into");
        BASE_FIELDS.put("identity.agentName","identity.agent_name");
        BASE_FIELDS.put("identity.agentPhone","identity.agent_phone");
        BASE_FIELDS.put("identity.agentQq","identity.agent_qq");
        BASE_FIELDS.put("identity.salaryPayType","identity.salary_pay_type");
        BASE_FIELDS.put("identity.alipayNo","identity.alipay_no");
        BASE_FIELDS.put("identity.alipayName","identity.alipay_name");
        BASE_FIELDS.put("identity.lifePhone1","identity.life_phone1");
        BASE_FIELDS.put("identity.lifePhone2","identity.life_phone2");
        BASE_FIELDS.put("identity.lifePhone3","identity.life_phone3");
        
    }

    @RequestMapping(value = "query", method = { RequestMethod.POST,RequestMethod.GET })
    public void query(String data) {
      try{
          List list=null;
          list.get(1);
      }catch (Exception ex)
      {
          ex.printStackTrace();
          logger.error("send");
      }
    }

    /**
     * 添加
     * @param data
     * @return
     */
    @RequestMapping(value = "add", method = { RequestMethod.POST, RequestMethod.GET })
    public @ResponseBody String add(String data) {
        try {
            HttpDataParam<WebUserModel> dataCondition = JsonUtil.parseObject(data, new TypeReference<HttpDataParam<WebUserModel>>(){});
            return webUserService.addWebUser(dataCondition);
        }catch(DataAccessException e){
            int code = super.getSqlErrorCode(e);
            if(code == IConstants.ResponseDefine.Code.ERROR_506.getIndex()){
                logger.warn("update error--param:"+ data + e.toString());
            }else{
                logger.error("update error--param:"+ data + e.toString());
            }
            return JsonUtil.toJSONString(new ResponseData(code,"SQL异常:"+e.getCause()),false);
        } catch (Exception e) {
            logger.error("add error--param:"+ data + e.toString(),e);
            return JsonUtil.toJSONString(new ResponseData(IConstants.ResponseDefine.Code.ERROR_500.getIndex(), "程序异常:"+e.toString()), false);
        }
    }
    
    /**
     * 修改
     * @param data
     * @return
     */
    @RequestMapping(value = "update", method = { RequestMethod.POST, RequestMethod.GET })
    public @ResponseBody String update(String data) {
        try {
            HttpDataParam<WebUserModel> dataCondition = JsonUtil.parseObject(data, new TypeReference<HttpDataParam<WebUserModel>>(){});
            return webUserService.updateWebUser(dataCondition);
        }catch(DataAccessException e){
            int code = super.getSqlErrorCode(e);
            if(code == IConstants.ResponseDefine.Code.ERROR_506.getIndex()){
                logger.warn("update error--param:"+ data + e.toString());
            }else{
                logger.error("update error--param:"+ data + e.toString());
            }
            return JsonUtil.toJSONString(new ResponseData(code,"SQL异常:"+e.getCause()),false);
        } catch (Exception e) {
            logger.error("add error--param:"+ data + e.toString(),e);
            return JsonUtil.toJSONString(new ResponseData(IConstants.ResponseDefine.Code.ERROR_500.getIndex(), "程序异常:"+e.toString()), false);
        }
    }


    @Test
    public void test()
    {
        SMTPAppender appender = new SMTPAppender();
        try {
            appender.setSMTPUsername("sendwarning@hefantv.com");
            appender.setSMTPPassword("ubBzS7ing");
            appender.setTo("wangpengyan@hexindai.com");
            appender.setFrom("Monitor--Error Log<sendwarning@hefantv.com>");
            // SMTP服务器 smtp.163.com
            appender.setSMTPHost("smtp.hefantv.com");
            appender.setLocationInfo(true);
            appender.setSubject("Test Mail From Log4J");
            appender.setLayout(new PatternLayout());
            appender.activateOptions();
            logger.addAppender(appender);
            logger.error("Hello World");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("Printing ERROR Statements", e);
        }
    }

}


